﻿using Aop.Api.Encryption;
using System;
using System.BLL;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IBLL;
using System.IO;
using System.Linq;
using System.MVC.Filters;
using System.MVC.Models;
using System.Web;
using System.Web.Mvc;

namespace System.MVC.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// 主页视图
        /// </summary>
        /// <returns></returns>
        [SystemAuthAttrbute]
        public ActionResult Index()
        {
            ViewBag.username = Session["UserName"].ToString();
            var dataid = Session["userid"];
            return View();
        }

        /// <summary>
        /// 登录视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }

/*        public JsonResult get11()
        {
            IBLL.ISystemManager systemManager = new BLL.SystemManager();
            var data = systemManager.GetAllData();
            return Json(data, JsonRequestBehavior.AllowGet);
        }*/

        /// <summary>
        /// 获取菜单列表数据信息
        /// </summary>
        /// <returns></returns>
        public JsonResult GetMenus()
        {
            ISystemManager systemManager = new SystemManager();
            var data = systemManager.GetMenuslists(int.Parse(Session["DepartMentId"].ToString()));
            GetMenusViewModels Menusdata = new GetMenusViewModels()
            {
                homeInfo = new homeInfos()
                {
                    title = "首页",
                    href = "/Home/Welcome"
                },
                logoInfo = new logoInfos()
                {
                    title = "优社区",
                    image = "/layuimini-v2/images/admin.jpg",
                    href = ""
                },
                menuInfo = data
            };
            if(Session["DepartMentId"].ToString() == "2")
            {
                Menusdata.logoInfo.image = "/layuimini-v2/images/user.jpg";
            }
            return Json(Menusdata, JsonRequestBehavior.AllowGet);
            //return File(@"~/layuimini-v2/api/init.json", "application/json");
        }

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="modes">登录用户信息</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Login(LoginViewModes modes)
        {
            if (ModelState.IsValid)
            {
                if (modes.LoginCode != Session["LoginCode"].ToString())
                {
                    return Json("验证码错误");
                }
                IStaffManager staffManager = new StaffManager();
                string StaffId;
                string DepId;
                string key = "ILIVEZENGZHIHUIL";
                CryptoHelper crypto = new CryptoHelper(key);
                string passWord = crypto.Encrypt(modes.PassWord);
                if (staffManager.Login(modes.UserName, passWord, modes.IsManager, out StaffId, out DepId))
                {
                    if (modes.rememberMe)
                    {
                        Response.Cookies.Add(new HttpCookie("userid")
                        {
                            Value = StaffId,
                            Expires = DateTime.Now.AddDays(7)
                        });
                        Response.Cookies.Add(new HttpCookie("UserName")
                        {
                            Value = System.Web.HttpContext.Current.Server.UrlEncode(modes.UserName),
                            Expires = DateTime.Now.AddDays(7)
                        });
                        Response.Cookies.Add(new HttpCookie("DepartMentId")
                        {
                            Value = DepId,
                            Expires = DateTime.Now.AddDays(7)
                        });
                    }
                    else
                    {
                        Session["UserName"] = modes.UserName;
                        Session["userid"] = StaffId;
                        Session["DepartMentId"] = DepId;

                    }
                    return Json("ok");
                }
                else
                {
                    return Json("账号密码错误");
                }
            }
            return Json("false");
        }



        /// <summary>
        /// 生成并返回验证码
        /// </summary>
        /// <param name="p">时间戳</param>
        /// <returns></returns>
        public byte[] GetVerifyCode(string p)
        {
            int codeW = 80;
            int codeH = 30;
            int fontSize = 16;
            string chkCode = string.Empty;
            //颜色列表，用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman" };
            //验证码的字符集，去掉了一些容易混淆的字符 
            char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
            Random rnd = new Random();
            //生成验证码字符串 
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            //写入Session、验证码加密
            Session["LoginCode"] = chkCode;
            //创建画布
            Bitmap bmp = new Bitmap(codeW, codeH);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线 
            for (int i = 0; i < 1; i++)
            {
                int x1 = rnd.Next(codeW);
                int y1 = rnd.Next(codeH);
                int x2 = rnd.Next(codeW);
                int y2 = rnd.Next(codeH);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
            }
            //将验证码图片写入内存流，并将其以 "image/Png" 格式输出 
            MemoryStream ms = new MemoryStream();
            try
            {
                bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
                return ms.ToArray();
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }
        }

        public ActionResult Welcome()
        {
            IBatchInputByExcelManager manager = new BatchInputByExcelManager();
            var data = manager.GetCountToWelcome().ToList();
            ViewBag.data = data;
            var data1 = manager.getMaterialListDtos();
            ViewBag.MateriaList = data1;
            return View();
        }

        public JsonResult GetDataToEcharts()
        {
            /*int[] data = new int[] { 120, 200, 150, 80, 70, 110 };*/
            IBatchInputByExcelManager manager = new BatchInputByExcelManager();
            var data = manager.GetEChartsToWelcome();
            return Json(new { data=data},JsonRequestBehavior.AllowGet);
        }
    }
}